<template>
	<div>
		<el-dialog title="选择用户" v-model="isShowDialog" width="750px">
			<el-table ref="multipleTableRef" :data="userList" stripe style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" />
				<el-table-column prop="username" label="用户名称" />
				<el-table-column prop="nickname" label="用户昵称" />
				<el-table-column label="关联角色" show-overflow-tooltip>
					<template #default="scope">
						<span>{{ scope.row.roles.map((v) => v.name).join(',') }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="created_at" label="创建时间" width="200"> </el-table-column>
			</el-table>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="close" size="default">取 消</el-button>
					<el-button type="primary" @click="confirm" size="default">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { getUserList } from '@/api/system/user';
const emit = defineEmits(['handleSelectList']);

const multipleTableRef = ref(null);

const userList = ref([]);
const getUserLists = async () => {
	let res = await getUserList({ isPage: 2 });
	if (res.code !== 0) return;
	userList.value = res.data;
};

const selUserList = ref([]);
const handleSelectionChange = (val) => {
	selUserList.value = val;
};

// 确认
const confirm = () => {
	emit('handleSelectList', selUserList.value);
	closeDialog();
};
// 取消
const close = () => {
	// emit('handleSelectList', []);
	closeDialog();
};

// 打开弹窗
const isShowDialog = ref(false);
const openDialog = async (data) => {
	await getUserLists();
	isShowDialog.value = true;
	if (data.length) {
		data.forEach((v) => {
			nextTick(() => {
				userList.value.find((v2) => {
					if (v.id === v2.id) {
						multipleTableRef.value.toggleRowSelection(v2, undefined);
					}
				});
			});
		});
	} else {
		nextTick(() => {
			multipleTableRef.value.clearSelection();
		});
	}
};
// 关闭弹窗
const closeDialog = () => {
	isShowDialog.value = false;
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped>
</style>